package com.unknownman.block.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lianziyou.chain.common.api.CommonPage;
import com.lianziyou.chain.common.api.CommonParam;
import com.lianziyou.chain.common.api.CommonResult;
import com.unknownman.block.entity.TContractLogs;
import com.unknownman.block.entity.TNft;
import com.unknownman.block.entity.TNftTransRecord;
import com.unknownman.block.entity.TTokenErc20;
import com.unknownman.block.mapper.TTokenSwapRecord;
import com.unknownman.block.mapper.TTokenTransRecord;
import com.unknownman.block.service.TContractLogsService;
import com.unknownman.block.service.TNftService;
import com.unknownman.block.service.TNftTransRecordService;
import com.unknownman.block.service.TTokenErc20Service;
import com.unknownman.block.service.TTokenSwapRecordService;
import com.unknownman.block.service.TTokenTransRecordService;
import com.unknownman.block.vo.NFTVO;
import com.unknownman.block.vo.TranLogVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.cloud.annotation.SystemResource;
import org.cloud.constant.CoreConstant;
import org.cloud.exception.BusinessException;
import org.cloud.utils.DataDimensionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api(description = "TranLogController", tags = "TranLogController")
@Validated
@RestController
@RequestMapping("/admin/tran")
@SystemResource(path = "/admin/tran")
@Slf4j
public class TranLogController {

    @Autowired
    private TContractLogsService contractLogsService;
    @Autowired
    private TNftService nftService;
    @Autowired
    private TNftTransRecordService transRecordService;
    @Autowired
    private TTokenErc20Service erc20Service;

    @Autowired
    TTokenTransRecordService tokenTransRecordService;

    @Value("${system.DataDimension.open:false}")
    private Boolean isSystemDataDimensionOpen;


    @ApiOperation("获取交易记录")
    @SystemResource(value = "/admin-getTranLogList", description = "获取交易记录", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.POST, value = "/getTranLogList")
    public CommonResult<CommonPage<TContractLogs>> getTranLogList(@RequestBody TranLogVO vo, @RequestParam(value = "sorts", required = false) String sorts)
        throws BusinessException {
        QueryWrapper<TContractLogs> where = new QueryWrapper<>();
        where.eq(!StringUtils.isEmpty(vo.getContractAddress()), "contract_address", vo.getContractAddress());
        where.eq(!StringUtils.isEmpty(vo.getTransFrom()), "trans_from", vo.getTransFrom());
        where.eq(!StringUtils.isEmpty(vo.getTransTo()), "trans_to", vo.getTransTo());
        where.eq(!StringUtils.isEmpty(vo.getTransHash()), "trans_hash", vo.getTransHash());
        where.eq(!ObjectUtils.isEmpty(vo.getStatus()), "status", vo.getStatus());
        where.like(!ObjectUtils.isEmpty(vo.getFirstTopic()), "first_topic", vo.getFirstTopic());

        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                where.in("contract_address", contractAddressDataDimension);
            }
        }
        return CommonResult.success(contractLogsService.findListByPage(vo.getPage(), vo.getLimit(), sorts, where));
    }

    @ApiOperation("获取NFT记录")
    @SystemResource(value = "/admin-getNFTList", description = "获取NFT记录", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.POST, value = "/getNFTList")
    public CommonResult<CommonPage<TNft>> getNFTList(@RequestBody NFTVO vo, @RequestParam(value = "sorts", required = false) String sorts) throws BusinessException {
        QueryWrapper<TNft> where = new QueryWrapper<>();
        where.eq(!StringUtils.isEmpty(vo.getOwnerAddress()), "owner_address", vo.getOwnerAddress());
        where.eq(!StringUtils.isEmpty(vo.getPreOwnerAddress()), "pre_owner_address", vo.getPreOwnerAddress());
        where.eq(!ObjectUtils.isEmpty(vo.getTokenId()), "token_id", vo.getTokenId());

        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                where.in("nft_address", contractAddressDataDimension);
            }
        }

        return CommonResult.success(nftService.findListByPage(vo.getPage(), vo.getLimit(), sorts, where));
    }

    @ApiOperation("获取NFT交易记录")
    @SystemResource(value = "/admin-getNFTTranList", description = "获取NFT交易记录", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.POST, value = "/getNFTTranList")
    public CommonResult<CommonPage<TNftTransRecord>> getNFTTranList(@RequestBody NFTVO vo, @RequestParam(value = "sorts", required = false) String sorts)
        throws BusinessException {
        QueryWrapper<TNftTransRecord> where = new QueryWrapper<>();
        where.eq(!StringUtils.isEmpty(vo.getHash()), "transaction_hash", vo.getHash());
        where.eq(!StringUtils.isEmpty(vo.getFromAddress()), "from_address", vo.getFromAddress());
        where.eq(!StringUtils.isEmpty(vo.getToAddress()), "to_address", vo.getToAddress());
        where.eq(!ObjectUtils.isEmpty(vo.getTokenId()), "token_id", vo.getTokenId());
        where.eq(!ObjectUtils.isEmpty(vo.getNftId()), "nft_id", vo.getNftId());
        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                where.in("nft_address", contractAddressDataDimension);
            }
        }
        return CommonResult.success(transRecordService.findListByPage(vo.getPage(), vo.getLimit(), sorts, where));
    }


    @ApiOperation("获取erc20持仓列表")
    @SystemResource(value = "/admin-getErc20List", description = "获取erc20持仓列表", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.POST, value = "/getErc20List")
    public CommonResult<CommonPage<TTokenErc20>> getErc20List(CommonParam pageParam, @RequestBody Map<String, Object> params) {
        QueryWrapper<TTokenErc20> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(params)) {
            params.forEach((column, value) -> {
                if (!StringUtils.isEmpty(value)) {
                    if (value instanceof Object[]) {
                        Object[] values = (Object[]) value;
                        queryWrapper.between(column, values[0], values[1]);
                    } else if (value instanceof List) {
                        List<Object> values = (List<Object>) value;
                        if (values.size() > 1) {
                            queryWrapper.between(column, values.get(0), values.get(1));
                        } else if (values.size() == 1) {
                            queryWrapper.ge(column, values.get(0));
                        }
                    } else {
                        queryWrapper.eq(column, value);
                    }

                }
            });
        }
        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                queryWrapper.in("token_address", contractAddressDataDimension);
            }
        }
        CommonPage<TTokenErc20> listByPage = erc20Service.findListByPage(pageParam.getPage(), pageParam.getLimit(), pageParam.getSorts(), queryWrapper);
        return CommonResult.success(listByPage);
    }

    @ApiOperation("获取erc20转账列表")
    @SystemResource(value = "/admin-getErc20TokenTransRecord", description = "获取erc20转账列表", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.POST, value = "/getErc20TokenTransRecord")
    public CommonResult<CommonPage<TTokenTransRecord>> getErc20TokenTransRecord(CommonParam pageParam, @RequestBody Map<String, Object> params) {

        QueryWrapper<TTokenTransRecord> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(params)) {
            params.forEach((column, value) -> {
                if (!StringUtils.isEmpty(value)) {
                    if (value instanceof List) {
                        List<Object> values = (List<Object>) value;
                        if (values.size() > 1) {
                            queryWrapper.between(column, values.get(0), values.get(1));
                        } else if (values.size() == 1) {
                            queryWrapper.ge(column, values.get(0));
                        }
                    } else if (value instanceof Object[]) {
                        Object[] values = (Object[]) value;
                        queryWrapper.between(column, values[0], values[1]);
                    } else {
                        queryWrapper.like(column, value);
                    }

                }
            });
        }
        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                queryWrapper.in("token_address", contractAddressDataDimension);
            }
        }
        CommonPage<TTokenTransRecord> listByPage = tokenTransRecordService.findListByPage(pageParam.getPage(), pageParam.getLimit(), pageParam.getSorts(),
            queryWrapper);
        return CommonResult.success(listByPage);
    }


    @Autowired
    TTokenSwapRecordService tokenSwapRecordService;

    @ApiOperation("获取Swap交易列表")
    @SystemResource(value = "/admin-getSwapTokenRecord", description = "获取Swap交易列表", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    @RequestMapping(method = RequestMethod.POST, value = "/getSwapTokenRecord")
    public CommonResult<CommonPage<TTokenSwapRecord>> getSwapTokenRecord(CommonParam pageParam, @RequestBody Map<String, Object> params) {
        QueryWrapper<TTokenSwapRecord> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(params)) {
            params.forEach((column, value) -> {
                if (!StringUtils.isEmpty(value)) {
                    if (value instanceof List) {
                        List<Object> values = (List<Object>) value;
                        if (values.size() > 1) {
                            queryWrapper.between(column, values.get(0), values.get(1));
                        } else if (values.size() == 1) {
                            queryWrapper.ge(column, values.get(0));
                        }
                    } else if (value instanceof Object[]) {
                        Object[] values = (Object[]) value;
                        queryWrapper.between(column, values[0], values[1]);
                    } else {
                        queryWrapper.like(column, value);
                    }

                }
            });
        }

        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                queryWrapper.in("pair_address", contractAddressDataDimension);
            }
        }
        CommonPage<TTokenSwapRecord> listByPage = tokenSwapRecordService.findListByPage(pageParam.getPage(), pageParam.getLimit(), pageParam.getSorts(),
            queryWrapper);
        return CommonResult.success(listByPage);
    }

}
